// utils/request.js

const baseURL = 'https://api.1001010.online'; // 替换为你的API基础URL

// 请求拦截器
const requestInterceptor = (config) => {
  // 在发送请求之前做些什么
  const token = uni.getStorageSync('token');
  if (token) {
    config.header.Authorization = `Bearer ${token}`;
	config.header.token = token
  }
  return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
  // 对响应数据做点什么
  console.log(response)
  const { data } = response;
	  return Promise.resolve(data);
};

// 错误处理
const handleError = (error) => {
  // 对错误做点什么
  console.error('请求错误:', error);
  
  return Promise.reject(error);
};

// 封装请求方法
const request = (options) => {
  // 合并默认配置和用户配置
  const config = {
    url: baseURL + options.url,
    method: options.method || 'GET',
    data: options.data || {},
    header: {
      'Content-Type': 'application/json',
      ...options.header
    },
    timeout: options.timeout || 60000,
    sslVerify: false // 忽略SSL证书验证，解决iOS端证书错误问题
  };
  
  // 应用请求拦截器
  const interceptedConfig = requestInterceptor(config);
  
  return new Promise((resolve, reject) => {
    uni.request({
      ...interceptedConfig,
      success: (res) => {
        try {
          const result = responseInterceptor(res);
          resolve(result);
        } catch (error) {
          reject(error);
        }
      },
      fail: (err) => {
        const error = handleError(err);
        reject(error);
      }
    });
  });
};

// 封装常用请求方法
export const get = (url, params = {}, options = {}) => {
  return request({
    url,
    method: 'GET',
    data: params,
    ...options
  });
};

export const post = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  });
};

export const put = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  });
};

export const del = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  });
};

export default {
  get,
  post,
  put,
  del
};